package com.fire8.dolphin.ui.fm;


import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.fire8.dolphin.common.Constants;
import com.fire8.dolphin.model.FmEntity;
import com.fire8.dolphin.ui.DolphinApplication;
import com.fire8.dolphin.ui.MainActivity;
import com.fire8.dolphin.ui.R;
import com.fire8.dolphin.ui.imgcache.AsynLoad;
import com.fire8.dolphin.ui.wiget.FmListAdapter;
import com.fire8.dolphin.ui.wiget.MenuHorizontalScrollView;
import com.fire8.dolphin.ui.wiget.SizeCallBackForMenu;
import com.fire8.dolphin.utils.LogUtil;
import com.fire8.dolphin.utils.StringUtil;
import com.fire8.dolphin.web.RequestUtils;

/**
 * 网络电台
 * <功能详细描述>
 * 测试：http://image.itings.cn/wizzardaudio1/201212/f7d27ca2-68bc-4d8c-8e8a-49ee72c9ced1.mp3
 * @author  lixg
 * @version [版本号,2013-1-3]
 * @see     [相关类/方法]
 * @since   [产品/模块]
 */
public class FMActivity extends ActivityGroup {
    private MenuHorizontalScrollView scrollView;
    private ListView menuList;
    
    private View playActivity;
    private Button menuBtn;
    private FmListAdapter menuListAdapter;
    private View[] children;
    private LayoutInflater inflater;
    private TextView tvPlayerName;
    private TextView tvTitle;
    private TextView tvDesc;
    private ImageView img;
    private TextView tvTotalTime;
    private TextView tvCurrTime;
    private ProgressBar progressBar;
    private ImageButton btnPlay;
    
    
    private List<FmEntity> list;
    private FmEntity currFm;//当前播放的
    private AsynLoad asynLoad;
    @Override
    public void onCreate(Bundle bundle) {
        
        super.onCreate(bundle);
        //String status = bundle.getString("status");
        
        inflater = LayoutInflater.from(this);
        asynLoad = new AsynLoad();
        setContentView(inflater.inflate(R.layout.menu_scroll_view, null));
        this.scrollView = (MenuHorizontalScrollView)findViewById(R.id.mScrollView);
        list = new ArrayList<FmEntity>();
        this.menuList = (ListView)findViewById(R.id.menuList);
        this.menuListAdapter = new FmListAdapter(this,list);
        this.menuList.setAdapter(menuListAdapter);
        this.menuList.setOnItemClickListener(onItemClick);
        
        this.playActivity = inflater.inflate(R.layout.fm_main, null);
        this.menuBtn = (Button)this.playActivity.findViewById(R.id.title_bt_left);
        this.menuBtn.setOnClickListener(onClickListener);
        getWegit();
        //默认先显示咨询页面
        //View temp = inflater.inflate(R.layout.topic, null);
        View leftView = new View(this);
        leftView.setBackgroundColor(Color.TRANSPARENT);
        children = new View[]{leftView, playActivity};
        this.scrollView.initViews(children, new SizeCallBackForMenu(this.menuBtn), this.menuList);
        this.scrollView.setMenuBtn(this.menuBtn);
        //this.scrollView.clickMenuBtn();
        //启动媒体播放器
        startPlayService();
    }
    
    @Override
    protected void onStart()
    {
        super.onStart();
        new RequestFmTask().execute("");
        //删除通知栏
        NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        mNotificationManager.cancel(FMActivity.class.hashCode());
    }
    
    /**在窗口关闭时，存着当前正在播放的状态**/
    @Override
    protected void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
    }

    private void startPlayService()
    {
        LogUtil.d("startPlayService");
        Intent intent = new Intent();
        intent.setAction("com.fire8.dolphin.service.MusicService");
        startService(intent);
        sendMessage(Constants.BACK_FM,"");
    }
    /**定义广播接收器**/
    private BroadcastReceiver receiver= new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context arg0, Intent intent)
        {
            int commend = intent.getIntExtra("command", 0);
            Object param;
            //LogUtil.d("commend:"+commend);
            switch (commend)
            {
                case Constants.MEDIA_INIT:
                    //已经初始化完成，准备播放，取得参数计算音乐总长度和时间
                    param = intent.getStringExtra("param");
                    initProgressBar((String)param);
                    break;
                case Constants.MEDIA_START:
                    //已暂停播放，将按钮图片设为播放按钮
                    currFm.setStatus(Constants.MEDIA_STATUS_PLAYING);
                    btnPlay.setTag("playing");
                    btnPlay.setImageResource(R.drawable.pause);
                    break;
                case Constants.MEDIA_PAUSE:
                    //已暂停播放，将按钮图片设为播放按钮
                    currFm.setStatus(Constants.MEDIA_STATUS_PAUSE);
                    btnPlay.setTag("pause");
                    btnPlay.setImageResource(R.drawable.play);
                    break;
                case Constants.MEDIA_STOP:
                    
                    break;
                case Constants.MEDIA_STATUS_PLAYING:
                    //播放中，更新进度条
                    param = intent.getStringExtra("param");
                    updateProgress((String)param);
                    break;
                case Constants.MEDIA_STATUS_STOP:
                    //放完了
                    currFm.setStatus(Constants.MEDIA_STATUS_STOP);
                    btnPlay.setTag("init");
                    btnPlay.setImageResource(R.drawable.play);
                    tvCurrTime.setText("00:00");
                    tvTotalTime.setText(" / 00:00");
                    progressBar.setProgress(0);
                    break;
                case Constants.MEDIA_BUFFER_UPDATE:
                    param = intent.getStringExtra("param");
                    //LogUtil.d("缓冲："+param);
                    
                    progressBar.setSecondaryProgress(Integer.valueOf((String)param) * progressBar.getMax()/100);
                    break;
                case Constants.BACK_FM:
                    //从service取得当前播放的音乐
                    FmEntity fm = (FmEntity)intent.getSerializableExtra("param");
                    if(fm != null)
                    {
                        int status=fm.getStatus();
                        if(Constants.MEDIA_STATUS_STOP == status)
                        {
                            break;
                        }
                        
                        currFm = fm;
                        initWegit();
                        String time = getTimeLong(currFm.getTimeLong());
                        tvTotalTime.setText(time);
                        progressBar.setMax(Integer.parseInt(String.valueOf(currFm.getTimeLong())));
                        
                        if(Constants.MEDIA_STATUS_PLAYING == status)
                        {
                            //将按钮设为暂停图片
                            btnPlay.setTag("playing");
                            btnPlay.setImageResource(R.drawable.pause);
                        }else if(Constants.MEDIA_STATUS_PAUSE == status)
                        {
                            //将按钮设为播放图片
                            btnPlay.setTag("pause");
                            btnPlay.setImageResource(R.drawable.play);
                            //暂停状态，将播放进度显示出来
                            updateProgress(String.valueOf(currFm.getCurrTime()));
                        }
                    }
                    break;
                default:
                    break;
            }
        }
        
    };
    private void getWegit()
    {
        tvTotalTime = (TextView)playActivity.findViewById(R.id.tv_fm_total_time);
        tvCurrTime = (TextView)playActivity.findViewById(R.id.tv_fm_curr_time);
        progressBar = (ProgressBar)playActivity.findViewById(R.id.progressbar01);
        tvPlayerName = (TextView)playActivity.findViewById(R.id.tv_player_name);
        tvTitle = (TextView)playActivity.findViewById(R.id.tv_fm_title);
        tvDesc = (TextView)playActivity.findViewById(R.id.tv_fm_desc);
        img = (ImageView)playActivity.findViewById(R.id.img_fm_image);
        
        btnPlay = (ImageButton)playActivity.findViewById(R.id.btn_play);
        btnPlay.setTag("init");//按钮为初始状态
        btnPlay.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                LogUtil.d("btnPlay click");
                //第一次进来，准备状态
                String tag = (String)btnPlay.getTag();
                if("init".equals(tag))
                {
                    //显示正在连接
                    tvTotalTime.setText("正在连接...");
                    sendMessage(Constants.MEDIA_INIT,currFm);
                }else if("pause".equals(tag))
                {
                    //如果现在是暂停状态，则发送播放命令
                    sendMessage(Constants.MEDIA_START,"");
                }else if("playing".equals(tag))
                {
                    //如果现在是播放状态，则发送暂停命令
                    sendMessage(Constants.MEDIA_PAUSE,"");
                }
            }
        });
        
        registerReceiver(this.receiver, new IntentFilter(Constants.PLAY_CALLBACK));
        
    }
    private void initWegit()
    {
        tvPlayerName.setText(currFm.getPlayer());
        tvTitle.setText(currFm.getTitle());
        tvDesc.setText(currFm.getDesc());
        if(!StringUtil.isEmpty(currFm.getImg()))
        {
            LogUtil.d("img:"+currFm.getImg());
            asynLoad.showimgAnsy(img,RequestUtils.IMG_URL+currFm.getImg());
        }
        btnPlay.setVisibility(View.VISIBLE);
        progressBar.setVisibility(View.VISIBLE);
        tvTotalTime.setText(" / 00:00");
        tvCurrTime.setText("00:00");
    }
    
    private void sendMessage(int command,String param)
    {
        Intent intent = new Intent(Constants.PLAY_CONTROL);
        Bundle bundle = new Bundle();
        bundle.putInt("command", command);
        bundle.putString("param", param);
        intent.putExtras(bundle);
        sendBroadcast(intent);
    }
    private void sendMessage(int command,FmEntity param)
    {
        Intent intent = new Intent(Constants.PLAY_CONTROL);
        Bundle bundle = new Bundle();
        bundle.putInt("command", command);
        bundle.putSerializable("param", (Serializable)param);
        intent.putExtras(bundle);
        sendBroadcast(intent);
    }
    
    /**开始播放，设置播放进度条**/
    private void initProgressBar(String param)
    {
        LogUtil.d("开始播放"+param);
        int len = Integer.valueOf(param);
        if(len >0)
        {
            String time = getTimeLong(len);
            tvCurrTime.setText("00:00");
            tvTotalTime.setText(time);
            progressBar.setMax(len);
            //将按钮设为暂停图片
            btnPlay.setTag("playing");
            btnPlay.setImageResource(R.drawable.pause);
        }
    }

    /** 计算音乐总时长**/
    private String getTimeLong(long len)
    {
        long min = len/1000/60;
        long sec = len/1000%60;
        String strMin = min+"";
        String strSec = sec+"";
        if(min/10 == 10)
        {
            strMin = "0"+min;
        }
        if(sec/10 == 10)
        {
            strSec = "0"+sec;
        }
        String time=" / "+strMin+":"+strSec;
        return time;
    }
    
    /**播放中，更新当前进度**/
    private void updateProgress(String param)
    {
        //LogUtil.d("播放："+param);
        int len = Integer.valueOf(param);
        if(len >0)
        {
            int min = len/1000/60;
            int sec = len/1000%60;
            String strMin = min+"";
            String strSec = sec+"";
            if(min/10 == 10)
            {
                strMin = "0"+min;
            }
            if(sec/10 == 10)
            {
                strSec = "0"+sec;
            }
            String time=strMin+":"+strSec;
            tvCurrTime.setText(time);
            progressBar.setProgress(len);
        }
    }
    
    /**重新设置播放状态**/
    private void initPlay()
    {
        tvPlayerName.setText(currFm.getPlayer());
        tvTitle.setText(currFm.getTitle());
        tvDesc.setText(currFm.getDesc());
        progressBar.setVisibility(View.VISIBLE);
        tvTotalTime.setText(" / 00:00");
        tvCurrTime.setText("00:00");
        if(!StringUtil.isEmpty(currFm.getImg()))
        {
            LogUtil.d("img:"+currFm.getImg());
            asynLoad.showimgAnsy(img,RequestUtils.IMG_URL+currFm.getImg());
        }
        sendMessage(Constants.MEDIA_INIT,currFm);
        
        //直接播放
        
    }
    
    /**当点击播放列表时，播放指定音乐**/
    private OnItemClickListener onItemClick = new OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id)
        {
            scrollView.clickMenuBtn();
            currFm = list.get(position);
            initPlay();
        }
        
    };
    private OnClickListener onClickListener = new OnClickListener(){

        @Override
        public void onClick(View arg0) {
            scrollView.clickMenuBtn();
        }
    };
    
    public MenuHorizontalScrollView getScrollView() {
        return scrollView;
    }

    public void setScrollView(MenuHorizontalScrollView scrollView) {
        this.scrollView = scrollView;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            LogUtil.d("FmActivity 按下了返回键");
            if (MenuHorizontalScrollView.menuOut == true)
            {
                this.scrollView.clickMenuBtn();
            }
            else
            {
                //弹出窗口提示是退出/隐藏/取消
                new AlertDialog.Builder(this)
                .setIcon(R.drawable.logo)
                .setTitle("温馨提示")
                .setMessage("您确定要退出海豚知音吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        //停止播放、关闭Service、签出、关闭程序、销毁程序
                        sendMessage(Constants.MEDIA_STOP,"");
                        //关闭Service
                        //Intent intent = new Intent();
                        //intent.setAction("com.fire8.dolphin.service.MusicService");
                        //stopService(intent);
                        //签出
                        RequestUtils.getInstall().checkout();
                        FMActivity.this.finish();
                    }
                })
                .setNeutralButton("隐藏", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        //显示到通知栏、程序不销毁
                        Intent mIntent = new Intent(FMActivity.this,MainActivity.class);  
                        //mIntent.putExtra("account", account);
                        //这里需要设置Intent.FLAG_ACTIVITY_NEW_TASK属性  
                        mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);      
                        PendingIntent mContentIntent =PendingIntent.getActivity(FMActivity.this,0, mIntent, 0);  
                        //这里必需要用setLatestEventInfo(上下文,标题,内容,PendingIntent)不然会报错.  
                        Notification notification = new Notification(R.drawable.logo,"正在播放:"+currFm.getTitle(),System.currentTimeMillis());  
                        notification.setLatestEventInfo(FMActivity.this, "海豚知音", currFm.getTitle(), mContentIntent);  
                        notification.defaults = Notification.DEFAULT_LIGHTS;
                        notification.ledARGB = 0xff00ff00;
                        notification.ledOnMS = 300;
                        notification.ledOffMS = 1000;
                        notification.flags = Notification.FLAG_SHOW_LIGHTS;
                        //这里发送通知(消息ID,通知对象)  
                        NotificationManager mNotificationManager = (NotificationManager)FMActivity.this.getSystemService(NOTIFICATION_SERVICE);
                        mNotificationManager.notify(FMActivity.class.hashCode(), notification); 
                        
                        FMActivity.this.finish();
                    }
                })
                .setNegativeButton("取消", null)
                .create().show();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
    /**获取FM信息**/
    class RequestFmTask extends AsyncTask<String, Void, String> 
    {
        @Override
        protected String doInBackground(String... arg0)
        {
            LogUtil.d("获取FM信息");
            try
            {
                if(RequestUtils.getInstall().isConnect(FMActivity.this))
                {
                    LogUtil.d("获取FM信息:"+DolphinApplication.URL+"fm/getFmList.php");
                    List<NameValuePair> param = new ArrayList<NameValuePair>();
                    param.add(new BasicNameValuePair("mac",""));
                    String json = RequestUtils.getInstall().getHttpJson(DolphinApplication.URL+"fm/getFmList.php", param);
                    LogUtil.d(""+json);
                    if(!StringUtil.isEmpty(json))
                    {
                        JSONObject data = new JSONObject(json);
                        String msgCode = data.getString("msgCode");
                        
                        if("1".equals(msgCode))
                        {
                            JSONArray jsonArray = data.getJSONArray("msgBody");
                            int len = jsonArray.length();
                            for (int i = 0; i < len; i++)
                            {
                                JSONObject obj = jsonArray.getJSONObject(i);
                                String id = obj.getString("id");
                                if(!StringUtil.isEmpty(id))
                                {
                                    FmEntity fm = new FmEntity();
                                    fm.setId(Integer.valueOf(id));
                                    fm.setDesc(obj.getString("desc"));
                                    fm.setImg(obj.getString("img"));
                                    fm.setPlayer(obj.getString("player"));
                                    fm.setTitle(obj.getString("title"));
                                    fm.setUrl(obj.getString("url"));
                                    fm.setTimeLong(obj.getLong("timeLong"));
                                    list.add(fm);
                                    LogUtil.d("图片："+fm.getImg());
                                }
                            }
                            return "1";
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LogUtil.e("获取FM信息失败",e);
            }
            return null;
        }
        
        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);
            if("1".equals(result))
            {
                LogUtil.d("获取FM信息返回");
                
                if(!list.isEmpty())
                {
                    menuListAdapter.notifyDataSetChanged();
                    if(currFm == null || currFm.getStatus() == Constants.MEDIA_STATUS_STOP)
                    {
                        currFm = list.get(0);
                        initWegit();
                    }
                    
                }
            }
        }
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
    
    
}
